package com.ktjy.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {
    //session工厂
    private static SqlSessionFactory factory;
    static {
        try{
            String resource="mybatis-config.xml";
            //加载Mybatis框架主配置文件
            InputStream is= Resources.getResourceAsStream(resource);
            //2、创建SqlSessionFactory
            factory=new SqlSessionFactoryBuilder().build(is);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获得session
    public static SqlSession createSession(){
        return factory.openSession(false);//关闭自动提交，开启事务控制
    }

    //关闭session
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
